package com.example.onlineeducation.ui.topic

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Handler
import android.os.Message
import android.view.View
import android.widget.SeekBar
import androidx.activity.result.ActivityResultLauncher
import com.example.onlineeducation.R
import com.example.onlineeducation.base.BaseActivity
import com.example.onlineeducation.databinding.StudyVideoFullScreenActivityBinding
import com.example.onlineeducation.utils.YcTimeUtils
import com.example.onlineeducation.viewmodel.StudyContentVM
import me.jessyan.autosize.internal.CustomAdapt

/**
 * SimpleDes:
 * Creator: Sindi
 * Date: 2022-04-06
 * UseDes:VideoView全屏
 * 添加第三方库 dp，sp适配：implementation'me.jessyan:autosize:1.2.1'
 */
class StudyVideoFullScreenActivity : BaseActivity<StudyVideoFullScreenActivityBinding>(StudyVideoFullScreenActivityBinding::inflate), CustomAdapt {
    private val mViewModel: StudyContentVM by ycViewModels()
    private val UPDATA_VIDEO_NUM = 1
    private var videoPath: String? = null
    private var currentPosition = 0

    companion object {
        private const val KEY_VIDEO_URL = "key_video_url"
        const val KEY_VIDEO_POSITION = "key_video_position"
        fun newInstance(activity: Context, videoUrl: String?, videoPosition: Int, launcher: ActivityResultLauncher<Intent>) {
            val intent = Intent(activity, StudyVideoFullScreenActivity::class.java).apply {
                putExtra(KEY_VIDEO_URL, videoUrl)
                putExtra(KEY_VIDEO_POSITION, videoPosition)
            }
            launcher.launch(intent)
        }

    }

    override fun StudyVideoFullScreenActivityBinding.initView() {
        videoPath = intent.getStringExtra(KEY_VIDEO_URL)
        currentPosition = intent.getIntExtra(KEY_VIDEO_POSITION, 0)
        initVideo()
    }

    private fun StudyVideoFullScreenActivityBinding.startPlayVideo() {
        videoPath = "http://ydkq.jsqqy.com/UpFile/video/video.mp4"
        videoView.setVideoURI(Uri.parse(videoPath))
        videoView.start()//视频播放时开始刷新
        handler.sendEmptyMessage(UPDATA_VIDEO_NUM)
        ivPlayOperation.setImageResource(R.drawable.ic_video_pause)
    }

    private fun StudyVideoFullScreenActivityBinding.initVideo() {
        if (currentPosition == 0) {
            dtvStartPlay.visibility = View.VISIBLE
        } else {
            startPlayVideo()
            dtvStartPlay.visibility = View.GONE
            videoView.seekTo(currentPosition)
        }

        dtvStartPlay.setOnClickListener {
            startPlayVideo()
            dtvStartPlay.visibility = View.GONE
            llVideoControl.visibility = View.VISIBLE
            llVideoTitle.visibility = View.VISIBLE
        }
        ivPlayOperation.setOnClickListener {
            if (videoView.isPlaying) {
                ivPlayOperation.setImageResource(R.drawable.ic_video_play)
                videoView.pause()//视频暂停
                handler.removeMessages(UPDATA_VIDEO_NUM)//当视频处于暂停状态，停止handler的刷新
            } else {
                ivPlayOperation.setImageResource(R.drawable.ic_video_pause)
                videoView.start()
                handler.sendEmptyMessage(UPDATA_VIDEO_NUM) //当视频播放时，通知刷新
            }
        }
        ivFullScreen.setOnClickListener {
            val intent = Intent()
            intent.putExtra(KEY_VIDEO_POSITION, currentPosition)
            setResult(RESULT_OK, intent)
            finish()
        }

        dtvBack.setOnClickListener {
            val intent = Intent()
            intent.putExtra(KEY_VIDEO_POSITION, currentPosition)
            setResult(RESULT_OK, intent)
            finish()
        }
        //播放进度条事件
        seekBarPlay.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                //设置当前的播放时间
                tvCurrentTime.text = YcTimeUtils.intMillisecondToStr(progress)
                if (videoView.duration == progress) {
                    ivPlayOperation.setImageResource(R.drawable.ic_video_pause)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {
                //拖动视频进度时，停止刷新
                handler.removeMessages(UPDATA_VIDEO_NUM)
            }

            override fun onStopTrackingTouch(seekBar: SeekBar) {
                val total = seekBar.progress //停止拖动后，获取总进度
                videoView.seekTo(total)  //设置VideoView的播放进度
                handler.sendEmptyMessage(UPDATA_VIDEO_NUM) //重新handler刷新
            }
        })
        videoView.setOnClickListener {
            if (llVideoControl.isShown) llVideoControl.visibility = View.GONE
            else llVideoControl.visibility = View.VISIBLE
            if (llVideoTitle.isShown) llVideoTitle.visibility = View.GONE
            else llVideoTitle.visibility = View.VISIBLE
        }
    }


    /**
     * 通过handler对播放进度和时间进行更新
     */
    @SuppressLint("HandlerLeak")
    private val handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == UPDATA_VIDEO_NUM) {
                mViewBinding.apply {
                    //获取视频播放的当前时间
                    val currentTime: Int = videoView.currentPosition
                    //获取视频的总时间
                    val totallyTime: Int = videoView.duration
                    tvTotalTime.text = YcTimeUtils.intMillisecondToStr(totallyTime)
                    tvCurrentTime.text = YcTimeUtils.intMillisecondToStr(currentTime)
                    //设置播放进度
                    seekBarPlay.max = totallyTime
                    seekBarPlay.progress = currentTime
                    //自己通知自己更新
                    sendEmptyMessageDelayed(UPDATA_VIDEO_NUM, 500) //500毫秒刷新
                }

            }
        }
    }

    override fun onResume() {
        super.onResume()
        mViewBinding.apply {
            videoView.seekTo(currentPosition)
        }
    }

    override fun onPause() {
        super.onPause()
        mViewBinding.apply {
            currentPosition = videoView.currentPosition
            handler.removeMessages(UPDATA_VIDEO_NUM)
            videoView.pause()//视频暂停
            ivPlayOperation.setImageResource(R.drawable.ic_video_play)
            llVideoControl.visibility = View.VISIBLE
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeMessages(UPDATA_VIDEO_NUM)
    }

    override fun isBaseOnWidth(): Boolean {
        return false
    }

    override fun getSizeInDp(): Float {
        return 360f
    }
}